//
//  FujinYDViewController.m
//  YeDian
//
//  Created by 罗西 on 3/29/16.
//  Copyright © 2016 罗西. All rights reserved.
//

#import "FujinYDViewController.h"
#import "Tools.h"
#import "ConfigData.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "JSON.h"
#import "MyFansTableViewCell.h"
#import "UIButton+WebCache.h"
#import "MJRefresh.h"
#import "fujinYDTableViewCell.h"
#import "yedianxiangqingViewController.h"
#import <CoreLocation/CLLocation.h>

@interface FujinYDViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSDictionary *myInfoDic;
    NSInteger currentPage;
}

@property (nonatomic,strong) UITableView *mainTableView;
@property (nonatomic,strong) NSMutableArray *itemsArray;
@property (nonatomic,strong) UISegmentedControl *control;

@end

@implementation FujinYDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    self.title = @"附近夜店";
    
    [self loadUI];
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadUI{
    _control = [[UISegmentedControl alloc]initWithItems:@[@"酒吧",@"ktv",@"会所"]];
    _control.frame = CGRectMake(-3, 0, SCREEN_WIDTH+6, 30);
    _control.tintColor = [UIColor redColor];
    _control.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_control];
    _control.selectedSegmentIndex = 0;
    
    [_control addTarget:self action:@selector(controllerPressed:) forControlEvents:UIControlEventValueChanged];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, SCREEN_HEIGHT-64-30)];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView setDataSource:self];
    [self.mainTableView setDelegate:self];
    [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.mainTableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];
    //[self.mainTableView launchRefreshing];
    
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        currentPage = 0;
        [self loadData];
    }];
    
    self.mainTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        currentPage++;
        [self loadData];
    }];
    
    currentPage = 0;
    _itemsArray = [NSMutableArray new];
    
    [self loadData];
    
}

- (void) controllerPressed:(UISegmentedControl*)sender {
    currentPage = 0;
    _itemsArray = [NSMutableArray new];
    [self loadData];
    
    /* 添加代码,处理值的变化 */
}

-(void)loadData{
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString* mp_ = [accountDefaults objectForKey:@"phone"];
    //NSString* mp_=[ud objectForKey:@"mp"];
    if (!mp_) {
        return;
    }
    NSLog(@"mp:%@",mp_);
    NSString* loginURL=HOST;

    loginURL=[loginURL stringByAppendingString:@"index.php/AppNearby/getNearByMerchantList"];
    
    
    
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    [req addPostValue:[accountDefaults objectForKey:@"uid"] forKey:@"uid"];
    [req addPostValue:[NSString stringWithFormat:@"%ld",(long)currentPage] forKey:@"currentPage"];
    [req addPostValue:[NSString stringWithFormat:@"%ld",(long)_control.selectedSegmentIndex+1] forKey:@"flag"];
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *_lng = [ud objectForKey:@"longitude"];
    NSString *_lat = [ud objectForKey:@"latitude"];
    if (_lng == nil) {
        _lng = @"0";
    }
    if (_lat == nil) {
        _lat = @"0";
    }
    [req addPostValue:_lng forKey:@"longi"];
    [req addPostValue:_lat forKey:@"lanti"];
    
    [req startSynchronous];
    NSError *error = [req error];
    NSLog(@"保存URL.loginURL==%@",req.url);
    
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        myInfoDic=[response JSONValue];
        NSString* uid=[myInfoDic objectForKey:@"uid"];
        NSLog(@"ID%@",uid);
        
        if (currentPage == 0) {
            _itemsArray = [NSMutableArray new];
        }
        
        [_itemsArray addObjectsFromArray:[myInfoDic objectForKey:@"list"]];
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer endRefreshing];
        [self.mainTableView reloadData];
        //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
    }else{
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer endRefreshing];
        NSLog(@"move failed:%@", [error localizedDescription]);
    }
}



#pragma mark UITableViewDelegate/UITableViewDataSource

/**
 *  每个cell有多少行
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


/**
 *  有多少个section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _itemsArray.count;
}

/**
 *  section的title
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return nil;
}

/**
 *  header的距离
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

/**
 *  row的高度
 */
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 80;
}

/**
 *  cell的属性
 */
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    fujinYDTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[fujinYDTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    NSDictionary* dic = [_itemsArray objectAtIndex:indexPath.section];
    NSString *str_logo = [NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"logo"]];
    NSString *str_name = [dic objectForKey:@"name"];
    NSString *str_desc = [dic objectForKey:@"qm"];
    if ([str_logo isEqual:[NSNull null]]) {
        str_logo = @"";
    }
    if ([str_name isEqual:[NSNull null]]) {
        str_name = @"";
    }
    if ([str_desc isEqual:[NSNull null]]) {
        str_desc = @"";
    }
    [cell.imgView setImageWithURL:[NSURL URLWithString:str_logo] forState:UIControlStateNormal];
    cell.nameLabel.text = str_name;
    cell.desLabel.text = str_desc;
    double lng;double lat;
    if (![[dic objectForKey:@"longi"] isEqual:[NSNull null]]) {
        lng = [[dic objectForKey:@"longi"]doubleValue];
    }
    if (![[dic objectForKey:@"lanti"] isEqual:[NSNull null]]) {
        lat = [[dic objectForKey:@"lanti"]doubleValue];
    }
    cell.disLabel.text = [self getDisByLng:lng lat:lat];
    cell.imgView.userInteractionEnabled = NO;
    cell.nameLabel.userInteractionEnabled = NO;
    cell.desLabel.userInteractionEnabled = NO;

    
    return cell;
}



-(NSString *)getDisByLng:(double)lng lat:(double)lat{
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    
    
    NSString *_lng = [ud objectForKey:@"longitude"];
    NSString *_lat = [ud objectForKey:@"latitude"];
    if (_lng == nil) {
        _lng = @"0";
    }
    if (_lat == nil) {
        _lat = @"0";
    }
    
    double lng_ = [_lng doubleValue];
    double lat_ = [_lat doubleValue];
    
    CLLocation *orig=[[CLLocation alloc] initWithLatitude:lat  longitude:lng];
    CLLocation* dist=[[CLLocation alloc] initWithLatitude:lat_ longitude:lng_];
    
    CLLocationDistance kilometers=[orig distanceFromLocation:dist]/1000;
    
    return [NSString stringWithFormat:@"%0.2f km",kilometers];
}

/**
 *  点击事件
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSUInteger row=[indexPath row];
    NSDictionary *dic=[_itemsArray objectAtIndex:indexPath.section];
    NSString* merchant_id=[dic objectForKey:@"merchant_id"];
    yedianxiangqingViewController* ui=[[yedianxiangqingViewController alloc] init];
    ui.title = @"夜店详情";
    ui.merchantId=[merchant_id intValue];
    [self.navigationController pushViewController:ui animated:NO];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
